/**
 * Created by wuyakun on 2017/8/11.
 * 会显示默认图片的image
 *
 * 解决 table 变形思路：https://ant.design/components/avatar-cn/
 * 使用  avatar 组件样式
 *
 * 模仿：https://github.com/ant-design/ant-design/blob/master/components/avatar/index.tsx
 */
import React, { Fragment } from 'react';
import Zmage from 'react-zmage';
import PropTypes from 'prop-types';
import Modal from 'drag-modal';
import { Avatar } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
import defaultImg from '../../../assets/images/default.png';

class DefaultImage extends React.Component {
  static propTypes = {
    src: PropTypes.string, //图片的路径，同src
    alt: PropTypes.string, //图片的alt, 同alt
    width: PropTypes.number, //图片的width, 同width
    shape: PropTypes.oneOfType(['circle', 'square']), //图片的形状，原型，还是方形，默认方形
  };

  static defaultProps = {
    src: null,
    alt: 'img',
    width: 60,
    shape: 'square',
  };

  constructor(props) {
    super(props);
    this.state = {
      src: this.props.src ? this.props.src : defaultImg,
      modalVisible: false,
      imgIsOK: true,
    };
  }

  componentDidMount() {
    this.state = {
      src: this.props.src,
      modalVisible: false,
      imgIsOK: true,
    };
  }

  /**
   * 这个方法很重要，否则 切换 table 的时候， 根本不会刷新 图片
   * @param nextProps
   * @param nextContext
   */
  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.src !== this.src) {
      this.state = {
        src: nextProps.src,
        modalVisible: false,
        imgIsOK: true,
      };
    }
  }

  render() {
    const { props, width = 60, shape = 'square', alt } = this.props;
    const { src } = this.state;
    /* eslint-disable react/jsx-no-bind */
    /**
     * 利用 Avatar 放到 table 里面不变形的原来，我们来处理，加上 Avatar 的css样式
     * <Avatar src={record} size={'large'} style={{cursor: 'zoom-in'}}
     */

    return (
      <Fragment>
        {/*查看图片或者附件的对话框*/}
        <Modal
          width={500}
          height={600}
          visible={this.state.modalVisible && this.state.imgIsOK}
          title=""
          destroyOnClose
          closable
          onCancel={() => {
            this.setState({
              modalVisible: false,
            });
          }}
          saveDistance={0}
          footer={null}
        >
          <Zmage src={this.state.src} alt="" style={{ width: '100%', cursor: 'pointer' }} />
        </Modal>

        {/*显示图片*/}
        <div
          className={classNames('ant-avatar')}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            this.setState({
              modalVisible: true,
            });
          }}
        >
          <Avatar
            src={src}
            size="large"
            shape={shape}
            alt={alt}
            style={{ cursor: 'default' }}
            onError={() => {
              this.setState({
                imgIsOK: false,
              });
            }}
          />
        </div>
      </Fragment>
    );
  }
}

export default DefaultImage;
